const express = require('express');
const cors = require('cors');
const path = require('path');
const uploadRouter = require('./routes/upload');
const userRoutes = require('./routes/userRoutes');
const recordRoutes = require('./routes/recordRoutes');
const foodRoutes = require('./routes/foodRoutes');
const recipeRoutes = require('./routes/recipeRoutes');
const communityRoutes = require('./routes/community');
const planRoutes = require('./routes/planRoutes');
const adminRoutes = require('./routes/adminRoutes');
const sequelize = require('./config/database');

const app = express();
const port = process.env.PORT || 3000;

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, '../public/uploads')));
app.use('/admin', express.static(path.join(__dirname, '../public/admin')));

// 路由
app.use('/api/upload', uploadRouter);
app.use('/api/users', userRoutes);
app.use('/api/records', recordRoutes);
app.use('/api/foods', foodRoutes);
app.use('/api/recipes', recipeRoutes);
app.use('/api/community', communityRoutes);
app.use('/api/plan', planRoutes);
app.use('/api/admin', adminRoutes);

// 全局错误处理
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({
    error: '服务器内部错误'
  });
});

// 数据库连接和服务器启动
async function startServer() {
  try {
    // 同步数据库模型
    await sequelize.sync();
    console.log('数据库连接成功');

    // 启动服务器
    app.listen(port, () => {
      console.log(`服务器运行在 http://localhost:${port}`);
    });
  } catch (error) {
    console.error('启动服务器失败:', error);
  }
}

startServer(); 